/**
 * 摄像头权限管理器
 * 专门处理 Vision Pro Safari 中的摄像头权限请求和状态检查
 */
export class CameraPermissionManager {
    constructor() {
        this.permissionStatus = 'unknown'; // 'granted', 'denied', 'prompt', 'unknown'
        this.isVisionPro = this.detectVisionPro();
        this.permissionCallbacks = new Set();
        this.retryCount = 0;
        this.maxRetries = 3;
    }

    /**
     * 检测是否为 Vision Pro 设备
     */
    detectVisionPro() {
        const userAgent = navigator.userAgent.toLowerCase();
        const isVisionOS = userAgent.includes('visionos') || 
                          userAgent.includes('vision pro') ||
                          (userAgent.includes('safari') && userAgent.includes('mobile') && 
                           window.DeviceOrientationEvent === undefined);
        
        console.log('🔍 设备检测:', {
            userAgent: navigator.userAgent,
            isVisionOS,
            hasWebXR: 'xr' in navigator,
            isSecureContext: window.isSecureContext
        });
        
        return isVisionOS;
    }

    /**
     * 检查当前摄像头权限状态
     * @returns {Promise<string>} 权限状态: 'granted', 'denied', 'prompt', 'unavailable', 'security_error'
     */
    async checkPermissionStatus() {
        try {
            // 检查安全上下文
            if (!window.isSecureContext) {
                console.warn('⚠️ 非安全上下文，摄像头权限可能不可用');
                this.permissionStatus = 'security_error';
                return 'security_error';
            }

            // 方法1: 使用 Permissions API (如果可用)
            if ('permissions' in navigator) {
                try {
                    const permission = await navigator.permissions.query({ name: 'camera' });
                    this.permissionStatus = permission.state;
                    console.log('📋 权限API状态:', permission.state);
                    
                    // 监听权限状态变化
                    permission.addEventListener('change', () => {
                        this.permissionStatus = permission.state;
                        console.log('🔄 权限状态变化:', permission.state);
                        this.notifyPermissionChange(permission.state);
                    });
                    
                    return permission.state;
                } catch (permError) {
                    console.warn('⚠️ Permissions API 查询失败:', permError);
                }
            }

            // 方法2: 尝试获取媒体流来检测权限
            return await this.testCameraAccess();
            
        } catch (error) {
            console.error('❌ 权限检查失败:', error);
            this.permissionStatus = 'unknown';
            return 'unknown';
        }
    }

    /**
     * 测试摄像头访问权限
     * @returns {Promise<string>} 权限状态
     */
    async testCameraAccess() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ 
                video: { 
                    facingMode: 'user',
                    width: { ideal: 640 },
                    height: { ideal: 480 }
                } 
            });
            
            // 立即停止流，我们只是检查权限
            stream.getTracks().forEach(track => track.stop());
            this.permissionStatus = 'granted';
            console.log('✅ 摄像头权限已授予');
            return 'granted';
            
        } catch (mediaError) {
            console.log('❌ 媒体访问错误:', mediaError.name, mediaError.message);
            
            if (mediaError.name === 'NotAllowedError') {
                this.permissionStatus = 'denied';
                return 'denied';
            } else if (mediaError.name === 'NotFoundError') {
                console.warn('⚠️ 未找到摄像头设备');
                this.permissionStatus = 'unavailable';
                return 'unavailable';
            } else if (mediaError.name === 'SecurityError') {
                console.warn('⚠️ 安全错误，需要HTTPS连接');
                this.permissionStatus = 'security_error';
                return 'security_error';
            } else {
                this.permissionStatus = 'prompt';
                return 'prompt';
            }
        }
    }

    /**
     * 请求摄像头权限
     * @returns {Promise<Object>} 权限请求结果
     */
    async requestCameraPermission() {
        console.log('🎥 开始请求摄像头权限...');
        
        try {
            // 检查安全上下文
            if (!window.isSecureContext) {
                throw new Error('需要HTTPS连接才能访问摄像头');
            }

            // 检查是否支持媒体设备API
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                throw new Error('此浏览器不支持摄像头访问');
            }

            // 显示权限请求提示
            this.showPermissionPrompt();
            
            // Vision Pro 特定的权限请求配置
            const constraints = {
                video: {
                    facingMode: 'user',
                    width: { ideal: 1280, min: 640 },
                    height: { ideal: 720, min: 480 },
                    frameRate: { ideal: 30, min: 15 }
                }
            };

            // 如果是Vision Pro，添加特定配置
            if (this.detectVisionPro()) {
                console.log('🥽 检测到Vision Pro，使用优化配置');
                constraints.video.frameRate = { ideal: 30, max: 60 };
            }
            
            const stream = await navigator.mediaDevices.getUserMedia(constraints);
            
            // 权限获取成功
            this.permissionStatus = 'granted';
            console.log('✅ 摄像头权限请求成功');
            
            // 停止测试流
            stream.getTracks().forEach(track => track.stop());
            
            // 隐藏提示
            this.hidePermissionPrompt();
            
            // 通知权限变化
            this.notifyPermissionChange('granted');
            
            return {
                success: true,
                status: 'granted',
                message: '摄像头权限已授予'
            };
            
        } catch (error) {
            console.error('❌ 摄像头权限请求失败:', error);
            
            this.hidePermissionPrompt();
            
            let errorMessage = '摄像头权限请求失败';
            let status = 'denied';
            
            switch (error.name) {
                case 'NotAllowedError':
                    errorMessage = '用户拒绝了摄像头权限';
                    status = 'denied';
                    // 如果是Vision Pro，显示权限指南
                    if (this.detectVisionPro()) {
                        setTimeout(() => this.showPermissionGuide(), 1000);
                    }
                    break;
                case 'NotFoundError':
                    errorMessage = '未找到摄像头设备';
                    status = 'unavailable';
                    break;
                case 'NotReadableError':
                    errorMessage = '摄像头被其他应用占用';
                    status = 'busy';
                    break;
                case 'OverconstrainedError':
                    errorMessage = '摄像头不支持请求的配置';
                    status = 'unsupported';
                    break;
                case 'SecurityError':
                    errorMessage = '安全错误：需要HTTPS连接';
                    status = 'security_error';
                    break;
                default:
                    errorMessage = `未知错误: ${error.message}`;
                    status = 'unknown_error';
            }
            
            this.permissionStatus = status;
            this.notifyPermissionChange(status);
            
            return {
                success: false,
                status,
                message: errorMessage,
                error
            };
        }
    }

    /**
     * 显示权限请求提示
     */
    showPermissionPrompt() {
        // 移除现有提示
        this.hidePermissionPrompt();
        
        const prompt = document.createElement('div');
        prompt.id = 'camera-permission-prompt';
        prompt.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        `;
        
        const content = document.createElement('div');
        content.style.cssText = `
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 40px;
            max-width: 400px;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.3);
        `;
        
        content.innerHTML = `
            <div style="font-size: 48px; margin-bottom: 20px;">📷</div>
            <h2 style="margin: 0 0 16px 0; color: #333; font-size: 24px; font-weight: 600;">
                ${this.isVisionPro ? 'Vision Pro 摄像头权限' : '摄像头权限请求'}
            </h2>
            <p style="margin: 0 0 24px 0; color: #666; font-size: 16px; line-height: 1.5;">
                ${this.isVisionPro 
                    ? '为了启用手部追踪功能，需要访问您的摄像头。请在弹出的权限对话框中选择"允许"。'
                    : '应用需要访问摄像头来启用手部追踪功能。请允许摄像头权限。'
                }
            </p>
            <div style="display: flex; align-items: center; justify-content: center; gap: 8px; color: #007AFF; font-size: 14px;">
                <div class="spinner" style="
                    width: 16px;
                    height: 16px;
                    border: 2px solid #E5E5EA;
                    border-top: 2px solid #007AFF;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                "></div>
                等待权限确认...
            </div>
        `;
        
        // 添加旋转动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);
        
        prompt.appendChild(content);
        document.body.appendChild(prompt);
    }

    /**
     * 隐藏权限请求提示
     */
    hidePermissionPrompt() {
        const prompt = document.getElementById('camera-permission-prompt');
        if (prompt) {
            prompt.remove();
        }
    }

    /**
     * 显示Vision Pro权限设置指南
     */
    showPermissionGuide() {
        if (!this.detectVisionPro()) {
            console.log('非Vision Pro设备，跳过权限指南');
            return;
        }

        // 移除已存在的指南
        this.hidePermissionGuide();

        const guide = document.createElement('div');
        guide.id = 'visionpro-permission-guide';
        guide.innerHTML = `
            <div style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.85);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 10000;
                font-family: -apple-system, BlinkMacSystemFont, sans-serif;
                backdrop-filter: blur(10px);
            ">
                <div style="
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 25px;
                    padding: 40px;
                    max-width: 600px;
                    text-align: center;
                    color: white;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                    border: 1px solid rgba(255, 255, 255, 0.2);
                ">
                    <div style="font-size: 60px; margin-bottom: 20px;">🥽</div>
                    <h2 style="color: white; margin-bottom: 25px; font-size: 24px; font-weight: 700;">
                        Vision Pro 摄像头权限设置
                    </h2>
                    <p style="margin-bottom: 30px; line-height: 1.6; font-size: 16px; opacity: 0.9;">
                        要在Vision Pro Safari中启用摄像头权限，请按照以下步骤操作：
                    </p>
                    <div style="
                        background: rgba(255, 255, 255, 0.1);
                        border-radius: 15px;
                        padding: 25px;
                        margin-bottom: 30px;
                        text-align: left;
                        backdrop-filter: blur(10px);
                    ">
                        <ol style="line-height: 2; font-size: 15px; margin: 0; padding-left: 20px;">
                            <li><strong>打开设置应用</strong> - 在主屏幕找到齿轮图标</li>
                            <li><strong>选择 Safari</strong> - 在应用列表中找到Safari浏览器</li>
                            <li><strong>找到摄像头选项</strong> - 在Safari设置中查找"摄像头"</li>
                            <li><strong>选择"允许"</strong> - 授予Safari访问摄像头的权限</li>
                            <li><strong>刷新页面</strong> - 返回Safari并重新加载当前页面</li>
                        </ol>
                    </div>
                    <div style="margin-bottom: 25px;">
                        <p style="font-size: 14px; opacity: 0.8; margin: 0;">
                            💡 提示：如果仍然无法访问摄像头，请确保您的Vision Pro系统版本支持Safari摄像头功能
                        </p>
                    </div>
                    <div style="display: flex; gap: 15px; justify-content: center;">
                        <button onclick="this.parentElement.parentElement.remove()" style="
                            background: rgba(255, 255, 255, 0.2);
                            color: white;
                            border: 2px solid rgba(255, 255, 255, 0.3);
                            padding: 12px 24px;
                            border-radius: 12px;
                            font-size: 16px;
                            font-weight: 600;
                            cursor: pointer;
                            backdrop-filter: blur(10px);
                            transition: all 0.3s ease;
                        " onmouseover="this.style.background='rgba(255,255,255,0.3)'" 
                           onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            我知道了
                        </button>
                        <button onclick="window.location.reload()" style="
                            background: #007AFF;
                            color: white;
                            border: 2px solid #007AFF;
                            padding: 12px 24px;
                            border-radius: 12px;
                            font-size: 16px;
                            font-weight: 600;
                            cursor: pointer;
                            transition: all 0.3s ease;
                        " onmouseover="this.style.background='#0056CC'" 
                           onmouseout="this.style.background='#007AFF'">
                            刷新页面
                        </button>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(guide);
        
        // 15秒后自动隐藏
        setTimeout(() => {
            this.hidePermissionGuide();
        }, 15000);
    }

    /**
     * 隐藏权限设置指导
     */
    hidePermissionGuide() {
        const guide = document.getElementById('camera-permission-guide');
        if (guide) {
            guide.remove();
        }
    }

    /**
     * 添加权限状态变化监听器
     */
    addPermissionListener(callback) {
        this.permissionCallbacks.add(callback);
    }

    /**
     * 移除权限状态变化监听器
     */
    removePermissionListener(callback) {
        this.permissionCallbacks.delete(callback);
    }

    /**
     * 通知权限状态变化
     */
    notifyPermissionChange(status) {
        this.permissionCallbacks.forEach(callback => {
            try {
                callback(status);
            } catch (error) {
                console.error('权限回调执行失败:', error);
            }
        });
    }

    /**
     * 获取当前权限状态
     */
    getPermissionStatus() {
        return this.permissionStatus;
    }

    /**
     * 检查是否有摄像头权限
     */
    hasPermission() {
        return this.permissionStatus === 'granted';
    }

    /**
     * 重置权限状态
     */
    reset() {
        this.permissionStatus = 'unknown';
        this.retryCount = 0;
        this.hidePermissionPrompt();
        this.hidePermissionGuide();
    }

    /**
     * 销毁管理器
     */
    dispose() {
        this.hidePermissionPrompt();
        this.hidePermissionGuide();
        this.permissionCallbacks.clear();
    }
}